package cn.fl.spl.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cmm.comm.facade.framework.api.ISysCtrlCfgApiService;
import cmm.comm.facade.framework.condition.SysCtrlCfgQueryCondition;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.fl.capital.transform.CapChnOvdRateVOTransform;
import cn.fl.capital.vo.CapChnOvdRateVO;
import cn.fl.spl.service.ISplHRiskLogService;
import cn.fl.spl.vo.SplHRiskLogVO;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.enums.SplRelLogBizTypCdNum;
import fl.spl.facade.spl.condition.SplHRiskLogQC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.Pager;
import cn.fl.capital.condition.CapChnOvdRateQC;
import cn.fl.capital.dto.CapChnOvdRateDTO;
import cn.fl.capital.service.ICapChnOvdRateApiService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.spl.service.ISplHRiskWarnRecService;
import cn.fl.spl.transform.SplHRiskWarnRecVOTransform;
import cn.fl.spl.vo.SplHRiskWarnRecVO;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.spl.facade.framework.constant.DictionaryConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.framework.enums.SplAudStsCdEnum;
import fl.spl.facade.spl.api.ISplHRiskWarnRecApiService;
import fl.spl.facade.spl.dto.SplHRiskWarnRecDTO;
import fl.spl.facade.store.api.ISplRelOpLogApiService;
import fl.spl.facade.store.condition.SplRelOpLogQC;
import fl.spl.facade.store.dto.SplRelOpLogDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;

/**
 * @Description: 供应商高风险预警表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class SplHRiskWarnRecServiceImpl implements ISplHRiskWarnRecService {

	@Autowired
	private ISplHRiskWarnRecApiService splHRiskWarnRecApiService; 
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private ISplRelOpLogApiService splRelOpLogApiService;
	@Autowired
	private ICapChnOvdRateApiService capChnOvdRateApiService;
	@Autowired
	private ISysCtrlCfgApiService sysCtrlCfgApiService;
	@Autowired
	private ISplHRiskLogService splHRiskLogService;

	@Override
	public SplHRiskWarnRecVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			return null;
		}
		//TODO 业务逻辑
		SplHRiskWarnRecDTO dto = null;//this.自定义ApiService.selectById(id);
		return SplHRiskWarnRecVOTransform.toVO(dto);
	}

	@Override
	public Long add(SplHRiskWarnRecVO entity) throws BaseException{
		if(null == entity){
			return null;
		}
		//return this.splHRiskWarnRecApiService.add(SplHRiskWarnRecVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return null;
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			return false;
		}
		//return this.splHRiskWarnRecApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
	@Override
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
			return false;
		};
		return false;
    }

	@Override
	public boolean modify(SplHRiskWarnRecVO entity) throws BaseException{
		if(null == entity){
			return false;
		}
		//return this.splHRiskWarnRecApiService.modify(SplHRiskWarnRecVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page){
			page = new Pager();
		}
		Pager resultPage = this.splHRiskWarnRecApiService.searchListPage(page, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		if (null != resultPage) {
			List<SplHRiskWarnRecDTO> dtoList = (List<SplHRiskWarnRecDTO>) resultPage.getResultList();
			List<SplHRiskWarnRecVO> voList = SplHRiskWarnRecVOTransform.toVOList(dtoList);
			
			Map<String, String> audStsCdMap = this.sysDictionaryApiService.searchGroupToMap(SplSystemConstant.FL_SYS_CD, 
					SplSystemConstant.DEFAULT_ORG_CD, DictionaryConstant.CODE_AUD_STS_CD);
			
			Map<String, String> opTypCdMap = this.sysDictionaryApiService.searchGroupToMap(SplSystemConstant.SPL_SYS_CD, 
					SplSystemConstant.DEFAULT_ORG_CD, DictionaryConstant.SPL_OP_TYP_CD);
			
			List<Long> opLogIdList = new ArrayList<>();
			for (SplHRiskWarnRecVO splHRiskWarnRecVO : voList) {
				opLogIdList.add(splHRiskWarnRecVO.getOpLogId());
			}
			SplRelOpLogQC opLogQC = new SplRelOpLogQC();
			opLogQC.setIdList(opLogIdList);
			List<SplRelOpLogDTO> opLogList = this.splRelOpLogApiService.searchSplRelOpLogList(opLogQC);
			Map<Long, SplRelOpLogDTO> opLogMap = new HashMap<>();
			for (SplRelOpLogDTO splRelOpLogDTO : opLogList) {
				opLogMap.put(splRelOpLogDTO.getId(), splRelOpLogDTO);
			}
			
			for (SplHRiskWarnRecVO vo : voList) {
				//封装返回对象
				if (StringUtils.isNotEmpty(vo.getAudStsCd())) {
                    if (!"99".equals(vo.getAudStsCd())) {
                        vo.setAudStsCdNm(audStsCdMap.get(vo.getAudStsCd()));
                    } else {
                        vo.setAudStsCdNm("变更审核中");
                    }
                } else {
					vo.setAudStsCdNm(SplAudStsCdEnum.NOTSUBMIT.getStatusNm());
				}
				if (StringUtils.isNotEmpty(vo.getOpLogId())) {
					vo.setOpTypCd(opLogMap.get(vo.getOpLogId()).getOpTypCd());
					vo.setOpTypCdNm(opTypCdMap.get(vo.getOpTypCd()));
				}
			}
			
			resultPage.setResultList(voList);
		}
		return resultPage;
	}
	
	@Override
	public DataResultDTO addHRiskWarnFlowStart(FlowStartParamsDTO flowStartParamsDTO) throws BaseException {
		if(StringUtils.isEmpty(flowStartParamsDTO.getCrtUsrId()) || StringUtils.isEmpty(flowStartParamsDTO.getBusinessKey())){
			BaseLogUtils.newWebLogger("用户ID和业务数据主键必须要存在").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			throw new BaseException(BaseExceptionConstant.COMMON_0001, "用户ID和业务数据主键必须要存在!");
		}
		return this.splHRiskWarnRecApiService.addHRiskWarnFlowStart(flowStartParamsDTO);
	}

	@Override
	public List<CapChnOvdRateVO> searchCapChnOvdRateList(CapChnOvdRateQC qc) throws BaseException {
		List<CapChnOvdRateDTO> resultDTO = this.capChnOvdRateApiService.searchListByCondition(qc);
		List<CapChnOvdRateVO> voList = null;
		if (CollectionUtils.isNotEmpty(resultDTO)) {
			voList = CapChnOvdRateVOTransform.toVOList(resultDTO);
		}
		
		//查询权重系数
		SysCtrlCfgQueryCondition ctrlCfgQueryCondition = new SysCtrlCfgQueryCondition();
		ctrlCfgQueryCondition.setCtrlCode(SplSystemConstant.SPL_OVD_SCORE_MODULUS);
		ctrlCfgQueryCondition.setOrgCd(SplSystemConstant.DEFAULT_ORG_CD);
		ctrlCfgQueryCondition.setSysCd(SplSystemConstant.SPL_SYS_CD);
		String modulusStr = this.sysCtrlCfgApiService.searchSysCtrlCfgByCtrlCode(ctrlCfgQueryCondition);
		Double modulus = Double.valueOf(modulusStr);

		//查询多头分
		SplHRiskLogQC hRiskLogQC = new SplHRiskLogQC();
		hRiskLogQC.setDataId(qc.getChnId());
		if ("1".equals(qc.getChnTypCd())) {
			hRiskLogQC.setDataTyp(SplRelLogBizTypCdNum.SPL.getBizTypCd());
		} else if ("2".equals(qc.getChnTypCd())) {
			hRiskLogQC.setDataTyp(SplRelLogBizTypCdNum.LNK.getBizTypCd());
		}
		hRiskLogQC.setIsNew(BaseConstant.IS_YESNO_YES);
		hRiskLogQC.setRiskTypCd("1");
		List<SplHRiskLogVO> splHRiskLogVOS = this.splHRiskLogService.searchList(hRiskLogQC);
		Double multiScore = 0D;
		if (CollectionUtils.isNotEmpty(splHRiskLogVOS) && null != splHRiskLogVOS.get(0) && StringUtils.isNotEmpty(splHRiskLogVOS.get(0).getRiskDesc())) {
			multiScore = Double.valueOf(splHRiskLogVOS.get(0).getRiskDesc());
		}

		//计算总分值
		if (CollectionUtils.isNotEmpty(voList)) {
			for (CapChnOvdRateVO vo : voList) {
				//总分值 ：（逾期分+时点逾期分+多头分）*权重系数
				if (StringUtils.isEmpty(vo.getEverScore())) {
					vo.setEverScore(0L);
				}
				if (StringUtils.isEmpty(vo.getPotScore())) {
					vo.setPotScore(0L);
				}
				vo.setTotalScore(DecimalUtils.mul((vo.getEverScore() + vo.getPotScore() + multiScore), modulus, 2));
			}
		}

		return voList;
	}
	
}
